<?php
require_once('to/Comentario.php');

class ComentariosDAO{
    const SEL_COMENTARIOS_POR_NOTA = "SELECT * FROM comentarios WHERE status = 'A' AND notaid = %d ORDER BY fechaCreado DESC";
	const COUNT_POR_NOTA = "SELECT count(comentid) as TotalComments FROM comentarios WHERE status = 'A' AND notaid = %d ORDER BY fechaCreado DESC";
    const INS_COMENTARIO = "INSERT INTO comentarios (notaid, user, email, comentario, ipAddress, fechaCreado, status) VALUES (%d, '%s', '%s', '%s', '%s', '%s', 'A')";

    public static function insertComentario($notaid, $user, $email, $comentario, $ipAddress, $fechaCredo, $status){
        $sSql = self::INS_COMENTARIO;

        $DB = DBFunctions::getInstance();
        $arrComentarios = $DB->execQ($sSql, array($notaid, $user, $email, $comentario, $ipAddress, $fechaCredo, $status));

        return $arrComentarios;
    }

	public static  function countComentariosPorNota($notaid){
		$sSql = self::COUNT_POR_NOTA;

		$DB = DBFunctions::getInstance();
		$arrComentarios = $DB->execSelect($sSql, array($notaid));

		return $arrComentarios[0]["TotalComments"];
	}

    public static function getComentariosPorNotaId($notaid){
        $sSql = self::SEL_COMENTARIOS_POR_NOTA;

        $DB = DBFunctions::getInstance();
        $arrComentarios = $DB->execSelect($sSql, array($notaid));

        return sizeof($arrComentarios);
    }

    public static function getNewComentariosPorNotaId($notaid){
        $sSql = self::SEL_COMENTARIOS_POR_NOTA;

        $DB = DBFunctions::getInstance();
        $arrComentarios = $DB->execSelect($sSql, array($notaid));

        return self::populate($arrComentarios);
    }
    
    /*This function get's the result array and builds a comentarios array object
      * @param array Comentarios result
      * @returns array with Comentarios objects */
    private static function populate($arrComentarios){

        $objComentarios = array();

        foreach($arrComentarios as $A){
            $objComentario = new Comentario();
            $objComentario->setComentId($A["comentid"]);
            $objComentario->setNotaId($A["notaid"]);
            $objComentario->setUser($A["user"]);
            $objComentario->setEmail($A["email"]);
            $objComentario->setComentario($A["comentario"]);
            $objComentario->setIpAddress($A["ipAddress"]);
            $objComentario->setFechaCreado($A["fechaCreado"]);
            $objComentario->setStatus($A["status"]);

            array_push($objComentarios, $objComentario);
        }
        return $objComentarios;
    }
}